import Vue from "vue";
import VueRouter from "vue-router";
import dayjs from "dayjs";
import wxHub from "@/lib/WxHub";

Vue.use(VueRouter);

import routes from "./routes.js";
import util from "@/lib/util";

var router = new VueRouter({routes});

router.beforeEach((to, from, next) => {
    if (to.matched.some(r => r.meta.auth)) {
        const token = util.cookies.get("token");
        const expiredAt = util.cookies.get("expired");
        // token存在 && 沒过期
        if (token && token !== "undefined" && expiredAt && dayjs() < dayjs(expiredAt)) {
            next();
        } else {
            // 没有登录的时候跳转到登录界面
            // 携带上登陆成功之后需要跳转的页面完整路径

            const code = util.getQueryString("code");
            const state = util.getQueryString("state");

            if (code && state) { // 如果带code和state参数，则是已授权还没写TOKEN
                // 授权跳转到登录页

                const query = {redirect: to.fullPath, code, state};
                next({name: "login", query});
            } else {
                // 跳转到授权界面
                const prefix = process.env.NODE_ENV !== "development" ? "/" : "/api/";
                const callbacl_url_prefix = location.origin + location.pathname;
                const redirect = `#${to.fullPath}`;
                const callback_url = `${callbacl_url_prefix}${encodeURIComponent(
                    redirect
                )}`;
                location.href = `${prefix}weixinAuth/?callback_url=${callback_url}`;
            }
        }
    } else {
        next();
    }
});

router.afterEach(to => {
    // 更改标题
    util.title(to.meta.title);
    if(to.meta.shareData){
        wxHub.start().then(wx=>{
            wx.updateAppMessageShareData(to.meta.shareData)
        })
    }
});

export default router;
